//单独运行无效，需要搭配其他脚本一起运行

//生成最小值到最大值之间的随机整数
function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}

function getScreenCapture(){
    let Thread = threads.start(function(){
        if(auto.service != null){  //如果已经获得无障碍权限
                //由于系统间同意授权的文本不同，采用正则表达式
                let Allow = textMatches(/(允许|立即开始|同意)/).findOne(10*1000);
                if(Allow){
                    Allow.click();
                }
        }
    });
    if(!requestScreenCapture()){
        log("请求截图权限失败");
        return false;
    }else{
        Thread.interrupt()
        log("已获得截图权限");
        return true;
    }
}

function 登录检测(loginT) {
    if (packageName("com.smile.gifmaker").textMatches(/登录后更精彩|登录后即可点赞|你还没有登录|立即登录|一键登录|验证并登录|请输入手机号|密码登录|手机号登录|[以]?其他登录方式|我已阅读并同意.*/).visibleToUser().findOnce()) {
        loginT = +new Date()
    } else if (id("com.smile.gifmaker:id/left_text").text("登录").visibleToUser().findOnce()) {
        loginT = +new Date()
    } else if (id("com.smile.gifmaker:id/featured_left_login").text("登录").visibleToUser().findOnce()) {
        loginT = +new Date()
    } else if (id("com.smile.gifmaker:id/one_key_login_btn").text("快速登录").visibleToUser().findOnce()) {
        loginT = +new Date()
    } 
    return loginT
}

function 登录检测时间比较(temp_loginT,loginT) {
    temp_loginT = 登录检测(loginT)
    if (!loginT) {
        if (temp_loginT) {
            loginT = temp_loginT
            log("检测到登录提示 - loginT = " + loginT)
        }
        exitsign = false
    } else {
        if ( temp_loginT - loginT > 60000) {
            log("登录检测距离上次已超 60秒 = " + temp_loginT)
            exitsign = false
            loginT = null 
        } else if ( temp_loginT - loginT > 10000) {
            loginT = temp_loginT
            log("登录检测距离上次已过 10秒 = " + loginT)
            exitsign = true
        } else if (temp_loginT === loginT && +new Date() - loginT > 30*1000) {
            log("持续未检测到登录且距离上次检测到已过 30秒 = " + loginT + "，将检测时间恢复成null，任务app应该已经被终止")
            exitsign = false
            loginT = null 
            temp_loginT = null
        }
    }
    //log("登录检测 exitsign = ",exitsign)
    return [temp_loginT,loginT,exitsign]
}

function 登录检测时间比较_old(temp_loginT,loginT) {
    temp_loginT = 登录检测(loginT)
    if (!loginT) {
        if (temp_loginT) {
            loginT = temp_loginT
            log("检测到登录提示 - loginT = " + loginT)
        }
        exitsign = false
    } else {
        if ( temp_loginT - loginT > 60000) {
            log("登录检测距离上次已超 60秒 = " + temp_loginT)
            exitsign = false
            loginT = null 
        } else if ( temp_loginT - loginT > 10000) {
            loginT = temp_loginT
            log("登录检测距离上次已过 10秒 = " + loginT)
            exitsign = true
        }
    }
    //log("登录检测 exitsign = ",exitsign)
    return [temp_loginT,loginT,exitsign]
}


function 停止脚本(){
    var curr = engines.myEngine();
    log("当前脚本 = ",curr + "");
    var currAll = engines.all();
    log("正在运行的脚本有", currAll.length, "个");
    for (var i = 0; i < currAll.length; i++) {
        if (currAll[i].toString() != curr.toString()) {
            log("停止脚本", currAll[i].toString());
            currAll[i].forceStop();
        }
    }

}

// 正则特殊字符转义函数
function escapeRegExp(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& 表示匹配到的整个字符
}

function 允许启动任务app() {
    if (textMatches(/Autox.* 想要打开 .*，是否允许？|启动应用/).findOne(300)) {
        let allow_ele = text("允许").className("android.widget.Button").visibleToUser().findOnce() 
        if (allow_ele) {
            allow_ele.click()
            sleep(200)
        }
    }
}

function 图色识别方式停止app() {
    if (getScreenCapture()) {
        let img = captureScreen()
        
    }


}


function 划掉任务app(fullname,package_name) {
    log("划掉任务app: ",fullname)
    launchPackage(package_name)
    允许启动任务app()
    if (!packageName(package_name).visibleToUser().findOne(1000)){
        log("未打开 fullname = ",fullname)
        return
    }
    log("已打开任务app，准备结束app")
    recents()
    
    //let re =new RegExp(fullname + "(,未加锁)?");
    //需先对 fullname 进行正则转义，避免特殊字符干扰。
    let re = new RegExp(escapeRegExp(fullname) + "(,未加锁)?");
    let ele_setting = descMatches(re).className("android.widget.FrameLayout").visibleToUser().findOne(1000)
    if (ele_setting) {
        log(ele_setting.desc())
        let bounds = ele_setting.bounds()
        let [l,t,r,b,cx,cy] = [bounds.left,bounds.top,bounds.right,bounds.bottom,bounds.centerX(),bounds.centerX()]
        let result = 滑动方向判断(l,t,r,b,cx,cy)
        //log("result is ",result)
        if (!result) { return false }
        else if (result == "left") { //向左滑动
            swipe(r-5, cy, l, cy, 500);
            return true
        } else if (result == "right") { //向右滑动
            swipe(l+5, cy, r, cy, 500);
            return true
        } else if (result == "top") { //向上滑动
            if (b - t >= 500) {
                swipe(cx, b-30, cx, t, 500);
                return true
            }
        }
    }
    return false
}

function 停止任务app() {
    log("强行停止任务new 是否退出exitsign = " + exitsign)
    openAppSetting(package_name);
    sleep(500)

    log("准备结束任务app = ",fullname)
    let 强行结束运行应用 = textMatches(/结束运行|.?.?强制.?.?|.?.?停止.?.?|.?.?结束.?.?/).visibleToUser().findOne(500);
    let remove_stop = false
    if (强行结束运行应用 ) {
        if (text(fullname).visibleToUser().findOnce()) {
            if (强行结束运行应用.text().length < 5) {
                log("存在强行停止按钮")
                click(强行结束运行应用.bounds().centerX(), 强行结束运行应用.bounds().centerY());
                remove_stop = true
            }
            if (text("强行停止").find().length > 0) {
                //正常情况
                let 强行停止 = text("强行停止").visibleToUser().findOne().bounds();
                click(强行停止.centerX(), 强行停止.centerY());
                remove_stop = true
            }
            if (text("确定").find().length > 0) {
                //正常情况
                let 强行停止 = text("确定").visibleToUser().findOne().bounds();
                click(强行停止.centerX(), 强行停止.centerY());
                remove_stop = true
            }
        }
    }
    if (remove_stop) {
        log("清理战场")
        划掉设置()
    }

}


// 记录实时点赞数据
function record_like(write_record, data) {
    if (write_record){
        files.write("点赞实时数据.txt", JSON.stringify(data,null,2), "utf-8");
    }
}


//小米有些时候识别不到节点
function swipeOnce(lastT,slidesign,author) {
    if (devicebrand !== "XIAOMI") { return [lastT,slidesign,author] }
    let currentT = +new Date()
    if (currentT - lastT < 5*1000){ return [lastT,slidesign,author] }
    //log("currentT - lastT = ",currentT - lastT)
    if (packageName("com.smile.gifmaker").textMatches(/我|消息|粉丝|关注/).findOnce()) {return [currentT,slidesign,author]}
    //if (!id("com.smile.gifmaker:id/texture_view_frame").className("android.widget.FrameLayout").visibleToUser().findOnce()) {return [lastT,slidesign,author] }
    if (!id("com.smile.gifmaker:id/root").desc("暂停视频").visibleToUser().findOnce()) {return [currentT,slidesign,author] }
    
    let current_author
    let ele = id("com.smile.gifmaker:id/user_name_text_view").textStartsWith("@").visibleToUser().findOnce()
    if (ele) {
        current_author = ele.text()
        if (author && current_author === author) {return [currentT,slidesign,current_author] }
    }
    
    if (devicebrand === "XIAOMI") {
        log("当前手机品牌为小米，准备查找展开按钮")
        //swipe(500,300,500,400,500)
        let ele = text("展开").findOne(500)
        if (ele) {
            log("已找到--展开")
            slidesign = true
            currentT = +new Date()
            let x = ele.bounds().centerX()
            let y =  ele.bounds().centerY()
            log("y坐标 = ",y)
            if (y > 300) {
                swipe(x, y, x, y - 100, 2000)
            } else {
                swipe(x ,y, x, y + 100, 2000)
            }
        }
    }
    return [currentT,slidesign,current_author]
}



function makeRecord4userNotExists(msg) {
    filename = "用户不存在.txt"
    try {
        if (!files.exists(filename)){
            let file = open(filename, "w"); //以写入模式（"w"）打开SD卡根目录下的example.txt文件。如果文件不存在，则会自动创建该文件。
            // 写入文本内容
            file.write(msg);
            // 关闭文件
            file.close();
        }
    } catch (e) {
        let file = open("error_" + filename, "w"); 
        file.write("捕获到错误：" + e.message); // `捕获到错误：${e.message}`;
        file.close();
    }
}
function userNotExists() {
    let clicksign = false
    if (text("用户不存在").visibleToUser().findOnce()) {
        clicksign = true
    }
    if (clicksign) {
        let ele = text("确定").visibleToUser().findOnce() || desc("确定").visibleToUser().findOnce()
        if (ele) {
            if (ele.clickable) {ele.click()}
            else {click(ele.bounds().centerX(), ele.bounds().centerY())}
            sleep(500)
        }

        return true
    }
    return false
}

function userNotExists_old() {
    let clicksign = false
    if (text("用户不存在").visibleToUser().findOnce()) {
        clicksign = true
        makeRecord4userNotExists('找到：text("用户不存在")')
    } else if (desc("用户不存在").visibleToUser().findOnce()) {
        clicksign = true
        makeRecord4userNotExists('找到：desc("用户不存在")')
    }
    if (clicksign) {
        let ele = text("确定").visibleToUser().findOnce() || desc("确定").visibleToUser().findOnce()
        if (ele) {
            if (ele.clickable) {ele.click()}
            else {click(ele.bounds().centerX(), ele.bounds().centerY())}
            sleep(500)
        }

        return true
    }
    return false
}

function 滑动方向判断(l,t,r,b,cx,cy) {
    //log("判断滑动方向")
    if (devicemodel.match(/KNT-AL10|KNT-UL10/)) {
        log("当前手机型号为 KNT-AL10 或者 KNT-UL10，将横向滑动结束'设置'程序")
        return "right"
    }
//    if (devicebrand === "XIAOMI") {
//        return "right/left" //节点在左半边和右半边的情况都有，向左向右滑都可以，也有可能有的手机是向上滑动的，所以下面用坐标方法来判断
//    }
    if (l < 0 || t < 0 && r < 0 && b < 0 || r - l < 100 || b - t < 100) { log("当前节点坐标不符合要求，不做处理"); return false }
    if ( deviceW/2 - (r - l) < deviceW * 0.1) { //节点左右坐标差值约为手机宽度一半(手机宽度一般为1080)，则说明节点界面约占左右一半的位置,
        //if (cx < deviceCx && Math.abs(deviceCx/2 - cx) < deviceW * 0.1) { return "left" } //节点在左边，并且节点中心和屏幕一半的一半的坐标相当，则确定节点在左边 --这种稍微有点复杂
        if (cx < deviceCx && r < deviceCx ) { return "left" } //节点在屏幕左半边
        else if (cx > deviceCx && l > deviceCx ) { return "right" } //节点在屏幕右半边
        else { return "top" }
    } else { return "top" }

}

function 划掉设置() {
    log("划掉应用信息")
    recents()
    sleep(500)
    let ele_setting = descMatches(/设置 应用信息(,未加锁)?/).className("android.widget.FrameLayout").visibleToUser().findOne(1000)
    if (ele_setting) {
        log(ele_setting.desc())
        let bounds = ele_setting.bounds()
        let [l,t,r,b,cx,cy] = [bounds.left,bounds.top,bounds.right,bounds.bottom,bounds.centerX(),bounds.centerX()]
        let result = 滑动方向判断(l,t,r,b,cx,cy)
        //log("result is ",result)
        if (!result) { return false }
        else if (result == "left") { //向左滑动
            swipe(r-5, cy, l, cy, 500);
            return true
        } else if (result == "right") { //向右滑动
            swipe(l+5, cy, r, cy, 500);
            return true
        } else if (result == "top") { //向上滑动
            if (b - t >= 500) {
                swipe(cx, b-30, cx, t, 500);
                return true
            }
        }
    }
    return false
}


function 点击取消(forcestop,exitsign,maxcount) {
    maxcount = maxcount || 10
    log("进入点击取消")
    //log("forcestop = ",forcestop)
    while (textMatches(/要强行停止吗.*|.*强行停止.*应用.*/).findOnce() || text("快手").visibleToUser().findOnce() && text("卸载").visibleToUser().findOnce()) {
        let ele = text("取消").visibleToUser().findOnce()
        if (ele){
            sleep(200)
            if (forcestop < maxcount) {
                ele.click()
            }
            sleep(300)
            if (exitsign) {forcestop = maxcount} //如果退出表示为true，则执行划掉设置程序
            if (forcestop >= maxcount) {
                if (划掉设置()) {
                    forcestop = 0
                    if (exitsign) {停止任务app()}
                }
                
            } else {
                log("切换到首页")
                home()
            }
            sleep(2000)
            return forcestop
        } else if (text("卸载").visibleToUser().findOnce()) {
            if (exitsign) {forcestop = maxcount} //如果退出表示为true，则执行划掉设置程序
            if (forcestop >= maxcount) {
                if (划掉设置()) {
                    forcestop = 0
                    if (exitsign) {停止任务app()}
                }
            } 
            for (let i = 1; i < 5; i++) {
                if (packageName("com.smile.gifmaker").textMatches(/我|消息|粉丝|关注/).findOnce() || descContains('点赞').visibleToUser().findOnce()) {
                   return forcestop
                } else if (!text("卸载").visibleToUser().findOnce()) {
                    return forcestop
                } 
                sleep(500)
            }
            return forcestop
        }
        sleep(500)
    }
    return forcestop
}



function 点赞(my_count,other_count,fail_count,uplimit) {
    log("进入点赞")
    let try_count = 0
    let sleepT = randInt(50,300)
    for (let i = 1; i < 10; i++) {
        //log("i = ",i)
        var elm = clickable(true).descStartsWith("未点赞，点赞").visibleToUser().findOne(1000)
        if (elm) {
            //log("elm.desc = ",elm.desc())
            sleep(sleepT)
            elm.click()
            sleep(500)
            if (descContains('已点赞').visibleToUser().findOnce())
            {   
                log("已点赞 -> my_count")
                my_count += 1
            } else {
                if (try_count < 1) {try_count += 1; sleepT = randInt(50,150); continue}
                log("点赞失败：点赞已达上限或者其他原因")
                fail_count += 1
            }
            break
        } else if (descContains('已点赞').visibleToUser().findOnce()) {   
            log("已点赞 -> other_count")
            other_count += 1
            break
        } //else { log("已点赞 和 未点赞都未检测到") }
        
    }
    return [my_count,other_count,fail_count,uplimit]

}

function likeUptoLimit(uplimit){
    let breaksign = false
    if (uplimit > 5) {
        toastLog("点赞已达上限,即将终止脚本")
        let ele_expand = text("展开").findOnce()
        if (ele) {
            click(ele_expand.bounds().centerX(), ele_expand.bounds().centerY())
            sleep(500)
            let ele_stop = text("停止运行").findOnce()
            let ele_exit = text("退出").findOnce()
            if (ele_stop && ele_exit) {
                click(ele_stop.bounds().centerX(), ele_stop.bounds().centerY())
                sleep(300)
                click(ele_exit.bounds().centerX(), ele_exit.bounds().centerY())
            }
        }
        let ele = textMatches(/展开|隐藏|停止运行|退出/).findOnce()
        if (!ele) {
            log("退出脚本成功，已完成点赞 ",my_count + other_count," 个")
            //break
            breaksign = true
        }
    }
    return breaksign 
}


var clearlog = true
var my_count = 0
var other_count = 0
var fail_count = 0
var uplimit = 0
let success_count = my_count + other_count
let total_count = success_count + fail_count

var forcestop = 0 //强行停止次数统计 大于20次，划掉强行停止
var devicebrand = device.brand.toUpperCase()
//var devicemodel = android.os.Build.MODEL
var devicemodel = device.model

var [deviceW,deviceH] = [device.width,device.height]
var [deviceCx,deviceCy] = [device.width/2,device.height/2]

var loginT = null //记录检测到登录提示的时间
var temp_loginT = loginT //记录检测到登录提示的临时变量
var exitsign = false //退出脚本标志

//任务app
let nameD = "all"
let nameB = "root"
let nameA = "免"
//任务app packageName
let fullname = nameA+nameB+"yolo"+nameD
let package_name = getPackageName(fullname)

var write_record = false
if (files.exists("是否记录.txt")){
    write_record = true 
 }
//events.observeToast();
//events.on("toast",function(toast){
//log("Toast内容: " + toast.getText() + " 包名: " + toast.getPackageName());
//});
toastLog("Running...")
while (true) {
    var now = new Date()
    // 使用getHours()方法获取当前小时
    var hours = now.getHours();
    if (hours == 4 && clearlog) {
        clearlog = false
        console.clear()
        log("当前时间在4-5点之间，清理一次日志")
    }
    let temp_count = total_count
    log("[成功 / 总计 = ", success_count," / ", temp_count,"], 补赞 = ",my_count,", 首赞 = ", other_count,", 失败 = ", fail_count)

    let temp_uplimit = uplimit
    let count4break = 0
    let startT
    var slidesign = false //小米手机获取节点不正常，用滑动元素方式测试是否可以增加节点刷新成功率
    var lastT = now.getTime() //用来记录（该while循环耗时）多久未成功识别到 点赞 元素，如果超过一定时间，则滑动元素
    let meetkwai = true //遇到[确定]快手之外的应用不点击取消，即不确定的也依然要点击取消
    let lastT4meetkwai//记录 变量 meetkwai 为 false 的起始时间，当超过一段时间，比如30秒，则重新将meetkwai置为true
    let stopcount = 0 //记录自停止任务app开始，持续未检测到快手界面的次数
    while (true) {
        ;[temp_loginT,loginT,exitsign] = 登录检测时间比较(temp_loginT,loginT)
        // if (textMatches(/你今天点赞的作品数已达上限/).findOnce()){ //这个节点autojs检测不到
        //     toastLog("点赞失败，点赞已达上限")
        //     uplimit += 1
        //     if ( count4break > 1 ) {break} } else 
        if (text("取消").visibleToUser().findOnce() && textMatches(/要强行停止吗.*|.*强行停止.*应用.*/).findOnce())  {
            if (!meetkwai) { sleep(2000); meetkwai = true; continue } //如果遇到非快手需要停止的，默认忽略不管
            log("已找到 强行停止/确定，取消/卸载")
            break 
        //} else if (text("快手").visibleToUser().findOnce() && text("卸载").visibleToUser().findOnce()) {
        } else if (text("卸载").visibleToUser().findOnce()) {
            //if (textMatches(/免rootyoloall|AScript|Autox.js.*|AutoJs.*/).visibleToUser().findOnce()) { sleep(500); continue }
            if  (!text("快手").visibleToUser().findOnce()) { 
                let tempT4meetkwai = +new Date()
                if (meetkwai) { if (!lastT4meetkwai || tempT4meetkwai - lastT4meetkwai > 30*1000) log("当前强行停止程序不是快手")};
                meetkwai = false;
                if (!lastT4meetkwai) {lastT4meetkwai = tempT4meetkwai;}
                if (tempT4meetkwai - lastT4meetkwai > 10*1000) {
                    lastT4meetkwai = tempT4meetkwai
                    meetkwai = true
                }
                sleep(500); 
                continue 
            }
            if ( count4break === 0 ) {startT = +new Date()}
            if ( count4break > 1 && +new Date() - startT > 5000 ) { home(); break }
            count4break += 1   
        } else if (count4break > 1 && (packageName("com.smile.gifmaker").textMatches(/我|消息|粉丝|关注/).findOnce() || descContains('点赞').visibleToUser().findOnce())) {
            break
        } else {
            let ele = id("com.smile.gifmaker:id/iv_close").className("android.widget.ImageView").findOnce() //clickable(true). 关闭更新弹窗
            if (ele)
            {
                ele.click()
                sleep(100)
                if ( count4break > 1 ) {break}
            } else if (userNotExists()) {
                //检测用户不存在--弹窗
            } else {
                //text = 妥妥好评/我要吐槽 >> 点击关闭按钮
                ele = clickable(true).id("com.smile.gifmaker:id/close").className("android.widget.ImageView").visibleToUser().findOnce() 
                if (ele) {ele.click();sleep(100)}
                else if (exitsign) { //如果上面各个元素都没有找到，并且此时 exitsign 为 true, 可能是没有跳转到强行停止界面
                    允许启动任务app()

                    if (packageName("com.smile.gifmaker").findOnce()) {
                        stopcount = 0
                        if (划掉任务app(fullname,package_name)) {
                            //exitsign = false
                        }
                    } else {
                        stopcount += 1
                    }
                    if (stopcount >= 10) {
                        log("任务app应该已经被停止了")
                        exitsign = false
                        temp_loginT = null
                        loginT = null
                        stopcount = 0
                    }
                }
            }
        }
        //var [lastT,slidesign,author] = swipeOnce(lastT,slidesign,author)
        sleep(500)
    }
    forcestop = 点击取消(forcestop,exitsign)
    //log("forcestop = ",forcestop)
    swipeOnce()
    var [my_count,other_count,fail_count,uplimit] = 点赞(my_count,other_count,fail_count,uplimit)
    success_count = my_count + other_count
    total_count = success_count + fail_count
    if (total_count > temp_count) {
        let data = {
            "成功 / 总计":success_count + " / " + total_count,
            "补赞":my_count,
            "首赞":other_count,
            "失败":fail_count,
            //time:now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds()
            //"Current_time":now.toString()
            "时间":"时分秒：" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds()
        }
        record_like(write_record,data)
        sleep(5000)
        if (devicebrand !== "XIAOMI") {
            forcestop += 1
        }
    }
    
    //let breaksign = likeUptoLimit(uplimit) 点赞达到上限，结束任务，现在取消了（有时候点赞上限还能点，而且这个点赞上限的toast消息用autojs抓不到）
    //if (breaksign) {break}

}